package grape.workflow.rest.flowable.ui.idm;

import grape.workflow.rest.flowable.ui.admin.MinimalDataGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.idm.api.IdmIdentityService;
import org.flowable.spring.boot.ldap.FlowableLdapProperties;
import org.flowable.ui.common.security.DefaultPrivileges;
import org.flowable.ui.idm.properties.FlowableIdmAppProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 重写该类，和 {@link MinimalDataGenerator}一样的问题
 * 但已经扩展了用户和组管理，这里不能再创建用了
 * Created by yangwei
 * Created at 2020/6/8 17:09
 */
@Slf4j
//@Component
public class IdmBootstrapper extends org.flowable.ui.idm.conf.Bootstrapper  {


    @Autowired
    private IdmIdentityService identityService;

    private FlowableLdapProperties ldapProperties;

    @Autowired
    private FlowableIdmAppProperties idmAppProperties;

    private Boolean inited = false;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null || event.getApplicationContext().getParent().getParent() == null) { // Using Spring MVC, there are multiple child contexts. We only care about the root
            if (inited) {
                return;
            }
            if (ldapProperties == null || !ldapProperties.isEnabled()) {
                if (idmAppProperties.isBootstrap()) {
                    // First create the default IDM entities
                    createDefaultAdminUserAndPrivileges();
                }

            } else {
                if (identityService.createPrivilegeQuery().privilegeName(DefaultPrivileges.ACCESS_IDM).count() == 0) {
                    String adminUserId = idmAppProperties.getAdmin().getUserId();
                    if (StringUtils.isNotEmpty(adminUserId)) {
                        initializeDefaultPrivileges(adminUserId);
                    } else {
                        log.warn(
                                "No user found with IDM access. Set flowable.idp.app.admin.user-id to give at least one user access to the IDM application to configure privileges.");
                    }
                }
            }
            inited = true;
        }
    }

    @Autowired(required = false)
    public void setLdapProperties(FlowableLdapProperties ldapProperties) {
        super.setLdapProperties(ldapProperties);
        this.ldapProperties = ldapProperties;
    }
}
